package com.samples.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Bora SAYINER
 * @since Jan 24, 2015 6:01:23 PM
 * @version 1.0
 */
@WebServlet(urlPatterns = { "/loginservlet.do" })
public class LoginServlet extends HttpServlet {

	private static final String DB_USER_NAME = "root";
	private static final String DB_PASSWORD = "Passw0rd";
	private static final String DB_URL = "jdbc:mysql://localhost:3306/login_sample";

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// StringBuffer stringBuffer = new StringBuffer();
		// Enumeration<String> parameterNames = req.getParameterNames();
		// while (parameterNames.hasMoreElements()) {
		// String paramName = parameterNames.nextElement();
		// String paramValue = req.getParameter(paramName);
		// if (paramValue.isEmpty()) {
		// stringBuffer.append("<font color='red'>"+paramName +
		// " boş bırakılamaz.</font><br/>");
		// }
		// }
		// resp.setCharacterEncoding("utf-8");
		// resp.getWriter().print(stringBuffer.toString());
		String message = "<font color='red'>Fail</font>";
		try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER_NAME, DB_PASSWORD)) {
			final String sqlCmd = "INSERT INTO users (first_name,last_name,email,password) VALUES (?,?,?,?)";
			try (PreparedStatement statement = connection.prepareStatement(sqlCmd)) {
				statement.setString(1, req.getParameter("firstName"));
				statement.setString(2, req.getParameter("lastName"));
				statement.setString(3, req.getParameter("email"));
				statement.setString(4, req.getParameter("password"));
				System.out.println(statement);
				int affectedRows = statement.executeUpdate();
				if (affectedRows > 0) req.getRequestDispatcher("index.jsp").forward(req, resp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		resp.getWriter().print(message);
	}

}
